const wx2my = require('../../wx2my');

var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');

var demo = new QQMapWX({
  key: '3NGBZ-BLF6N-RXPFK-SPZSN-2EXFE-KWFUW' //申请的Key

});

const api = require('../../utils/user_api_miniprogram.js');

const app = getApp();
Page({
  data: {
    wrap: true,
    have_coupon: true,
    acceptRule: false,
    openAgain: 'openAgain',
    model: '',
    macno: '',
    phoneNum: '',
    marker: '',
    list: [],
    code: '',
    stopPull: '',
    markers: [],
    key: "3NGBZ-BLF6N-RXPFK-SPZSN-2EXFE-KWFUW",
    centerlat: 0,
    centerlon: 0,
    rfid: '',
    tradeid: '',
    tradeno: '',
    num: 1,
    minusStatus: 'disable',
    minusStatus1: 'normal',
    maxNum: 3,
    videoLink: '',
    appCode: '',
    wrap2: true,
    showPrivacy: false,
    trade_id: "",

    marker_msg: false,
    noCar: true,
    underway: true,
    have_order: true,
    doorOPenfail: true,
    powerFail: true,
    handFail: true,
    noChest: true,
    no_order: true,
    openSus: true,
    paySus: true,
    handBackagain: 'handBackagain',
    powerBackagain: 'powerBackagain',
    latitude: '',
    longitude: '',
    handBackMistake: 'handBackMistake',
    backMistake: true,
    have_twoOrder: true
  },

  onTabItemTap() {
    console.log('切换到了 首页');
    // this.selectComponent('#privacy-popup-index').tabBarPageShow();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    console.log('切换到了 首页');
    // this.selectComponent('#privacy-popup-index').tabBarPageShow();
    // this.getvideoLink();
    this.setData({
      model: '',
      macno: ''
    });
    let that = this;

    if (e.trade_id) {
      that.setData({
        paySus: false
      });
    }

    if (e.q) {
      if (e.q.indexOf('coupon_id') > 0) {
        let url = decodeURIComponent(e.q);
        let coupon_id = app.fm.getUrlParam('coupon_id', url);
        var msgToken = wx2my.getStorageSync('token');

        if (msgToken == '' || msgToken == null) {
          that.setData({
            wrap: false,
            coupon_id: coupon_id
          });
        } else {
          that.setData({
            wrap: true,
            coupon_id: coupon_id
          });
          that.get_coupon();
        }
      } else if (e.q.indexOf('macno') > 0) {
        let url = decodeURIComponent(e.q);
        let macno = app.fm.getUrlParam('macno', url);
        that.setData({
          macno: macno
        });
        app.wxRequest2('ZhanHuiLogin', {
          // 展会租借随机开柜并登录系统
          'macno': macno
        }, function (res) {
          if (res.data.code == 1) {
            let token = res.data.data.token;
            wx2my.setStorageSync('token', token);
            that.setData({
              model: 'open_timeout',
              macno: "",
              isZhanHui: true
            });
          } else {
            that.get_status();
          }
        });
      } else if (e.q.indexOf('rfid') > 0) {
        let url = decodeURIComponent(e.q);
        let rfid = app.fm.getUrlParam('rfid', url);
        that.setData({
          rfid: rfid
        }); // that.get_status()
      } else if (e.q.indexOf('tradeid') > 0) {
        let url = decodeURIComponent(e.q);
        let tradeid = app.fm.getUrlParam('tradeid', url);
        that.setData({
          tradeid: tradeid
        });
      }
    }

    wx2my.getSystemInfo({
      success: function (res) {
        //设置map高度，根据当前设备宽高满屏显示
        that.setData({
          view: {
            Height: res.windowHeight,
            Width: res.windowWidth
          }
        });
      }
    });
  },
  onReady: function () {// setTimeout(() => {
    //   this.permiss()
    // }, 200)
  },

  //扫码获取优惠券
  get_coupon() {
    let that = this;
    app.wxRequest('receive_coupon', {
      'coupon_id': that.data.coupon_id
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        app.wxRequest('scan_code', {
          'coupon_id': that.data.coupon_id
        }, function (res) {
          console.log(res);

          if (res.data.code == 1) {
            that.setData({
              money: res.data.data.money,
              end_time: res.data.data.end_time,
              have_coupon: false
            });
          }
        });
      } else {
        app.toast(res.data.msg);
      }
    });
  },

  // 同意规则
  bindAcceptRule: function (e) {
    let that = this;
    that.data.acceptRule = !that.data.acceptRule;

    if (that.data.acceptRule == true) {
      this.acceptRule = true;
    } else {
      this.acceptRule = false;
    }
  },
  // 授权登陆
  getUserProfile: function (e) {
    console.log(e);
    let that = this;

    if (that.data.acceptRule) {
      wx2my.showLoading({
        title: '正在登录'
      });
      app.fm.wx_login((flag, userInfo) => {
        if (flag == 2) {
          that.setData({
            wrap: true
          });

          if (that.data.coupon_id) {
            that.get_coupon();
          }

          wx2my.hideLoading();
        } else if (flag == 3) {
          wx2my.hideLoading();
        }
      }, app);
    } else {
      app.toast("请点击同意《用户协议》");
    }
  },
  onShow: function () {
    this.setData({
      model: ''
    });
    let that = this;
    that.get_phone();

    // if (!wx2my.getStorageSync('showPrivacy')) {
    //   that.selectComponent('#privacy-popup-index').popUp();
    // } else {
      api.user_location(function (res) {
        console.log(res);

        if (res.code == 1) {
          that.getLocation_fn();
        } else if (res.code == 0) {
          wx2my.showModal({
            title: '提示',
            content: '请前往设置界面打开权限！',

            success(res) {
              if (res.confirm) {
                console.log('用户点击确定');
                wx2my.openSetting({
                  success(data) {
                    console.log(data.authSetting["scope.userLocation"]);

                    if (data.authSetting["scope.userLocation"] == true) {
                      wx2my.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 2000,

                        success() {}

                      });
                    }
                  }

                });
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }

          });
        }
      });
    // }
     // wx.getPrivacySetting({
    //   success: res => {
    //     console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
    //     if (res.needAuthorization) {
    //       // 需要弹出隐私协议
    //       that.selectComponent('#privacy-popup-index').popUp();
    //     } else {
    //       // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用隐私接口
    //       console.log("------------");
    //       api.user_location(function (res) {
    //         console.log(res);
    //         if (res.code == 1) {
    //           that.getLocation_fn();
    //         } else if (res.code == 0) {
    //           wx.showModal({
    //             title: '提示',
    //             content: '请前往设置界面打开权限！',
    //             success(res) {
    //               if (res.confirm) {
    //                 console.log('用户点击确定')
    //                 wx.openSetting({
    //                   success(data) {
    //                     console.log(data.authSetting["scope.userLocation"])
    //                     if (data.authSetting["scope.userLocation"] == true) {
    //                       wx.showToast({
    //                         title: '授权成功',
    //                         icon: 'success',
    //                         duration: 2000,
    //                         success() {}
    //                       })
    //                     }
    //                   }
    //                 })
    //               } else if (res.cancel) {
    //                 console.log('用户点击取消')
    //               }
    //             }
    //           })
    //         }
    //       });
    //     }
    //   },
    //   fail: () => {},
    //   complete: () => {}
    // })

  },

  //获取客服电话
  get_phone() {
    let that = this;
    app.wxRequest('customer', {
      'type': 3
    }, function (res) {
      console.log(res.data.data.tel);

      if (res.data.code == 1) {
        that.setData({
          phoneNum: res.data.data.tel
        });
      }
    });
  },

  center(e) {
    let that = this;
    wx2my.navigateTo({
      url: '/pages/user_center/user_center'
    });
  },

  getLocation_fn: function () {
    let that = this;
    wx2my.getLocation({
      type: 'gcj02',

      success(res) {
        console.log("-=-==-=-as=-d=-a-=d=--==-=",res);
        let markers = [];
        markers.push({
          id: -1,
          latitude: res.latitude,
          longitude: res.longitude,
          width: 30,
          height: 30,
          name: 'hello',
          iconPath: "/img/40.png",
          title: "",
          anchor: {
            x: .5,
            y: .5
          },

          callout: {
            content: "附近柜子 >",
            color: "#000000",
            bgColor: "#ffffff",
            fontWeight: "700",
            display: "ALWAYS",
            fontSize: "12",
            borderRadius: "5",
            padding: "10"
          }
        });
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          centerlat: res.latitude,
          centerlon: res.longitude,
          markers: markers
        });
        console.log(res.latitude);
        that.get_markers(); //获取标注点
      },

      fail(e) {}

    });
  },
  get_markers: function () {
    let that = this;
    let markers = that.data.markers;
    console.log(that);
    app.wxRequest('nearby', {
      'lat': that.data.latitude,
      'lng': that.data.longitude
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        let markers = that.data.markers;
        let list = res.data.data;
        console.log(list);
        list.forEach((item, index) => {
          markers.push({
            id: index,
            latitude: 10,
            longitude: 10,
            width: 30,
            height: 30,
            title: "",
            anchor: {
              x: .5,
              y: .5
            }
          });
        });
        that.setData({
          shop: list,
          markers: markers
        });
      } else {
        app.toast(res.data.msg);
      }
    });
  },

  //点击merkers
  markertap(e) {
    console.log(e);

    if (e.markerId < 0) {
      return false;
    } else {
      console.log(this.data.shop[e.currentTarget.markerId]);
      this.setData({
        marker_msg: true,
        using_show: false,
        current_marker: this.data.shop[e.currentTarget.markerId]
      });
    }
  },

  // controltap(e) {
  //   var that = this; //重新定位
  //   //重新定位

  //   let mapCtx = wx.createMapContext("map");
  //   var latitude, longitude;
  //   mapCtx.getCenterLocation({
  //     success: function (res) {
  //       latitude = res.latitude;
  //       longitude = res.longitude;
  //     }
  //   }); // //获取当前地图的中心经纬度
  //   // mapCtx.includePoints({
  //   //     padding:[10],
  //   //     points:[{
  //   //         latitude:latitude,
  //   //         longitude:longitude
  //   //     }]
  //   // })
  //   // mapCtx.translateMarker({
  //   //     markerId: -1,
  //   //     autoRotate: true,
  //   //     duration: 100,
  //   //     destination: {
  //   //         latitude:latitude,
  //   //         longitude:longitude,
  //   //     },
  //   //     animationEnd() {
  //   //         console.log('animation end')
  //   //     }
  //   // })

  //   mapCtx.moveToLocation();
  // },

  destination(e) {
    //导航
    console.log(e);
    wx2my.openLocation({
      latitude: e.currentTarget.dataset.lat * 1,
      longitude: e.currentTarget.dataset.lng * 1,
      scale: 28,
      name: e.currentTarget.dataset.address,
      address: e.currentTarget.dataset.address
    });
  },

  sendZhanHuiDevice(macno) {
    let that = this;
  },

  //判断用户租借状态
  //-22 有进行中的订单 -33 有一个未支付订单   -55 暂无空柜可租借 -44暂不可租借 您有两个正在进行中的订单
  get_status() {
    let that = this;
    app.wxRequest('rentToyCar', {
      'token': wx2my.getStorageSync('token'),
      'macno': that.data.macno ? that.data.macno : '',
      'rfid': that.data.rfid ? that.data.rfid : ''
    }, function (res) {
      console.log(res);

      if (res.data.code == -22) {
        that.setData({
          model: 'underway'
        });
      } else if (res.data.code == -33) {
        that.setData({
          model: 'haveOrder',
          macno: ''
        });
      } else if (res.data.code == -44) {
        that.setData({
          model: 'no_rent',
          macno: ''
        });
      } else if (res.data.code == -55) {
        that.setData({
          model: 'no_car',
          macno: ''
        });
      } else if (res.data.code == 1) {
        that.setData({
          macno: that.data.macno
        });
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
      }
    });
  },

  bindcallouttap(e) {
    // console.log(this.data.centerlat);
    // let mapCtx = wx.createMapContext('map');
    // mapCtx.getCenterLocation({
    //   success: res => {
    //     let longitude = res.longitude.toFixed(6);
    //     let latitude = res.latitude.toFixed(6);
    //     this.setData({
    //       centerlat: latitude,
    //       centerlon: longitude
    //     });
    //     wx2my.navigateTo({
    //       url: '/pages/near_store/near_store?centerlat=' + this.data.centerlat + "&centerlon=" + this.data.centerlon
    //     });
    //   }
    // });
  },

  get_toRentStatus() {
    let that = this;
    app.wxRequest('rentToyCar', {
      'token': wx2my.getStorageSync('token'),
      'macno': that.data.macno ? that.data.macno : '',
      'rfid': that.data.rfid ? that.data.rfid : ''
    }, function (res) {
      console.log(res);

      if (res.data.code == -22) {
        that.setData({
          model: 'underway'
        });
      } else if (res.data.code == -33) {
        that.setData({
          model: 'haveOrder',
          macno: ''
        });
      } else if (res.data.code == -44) {
        that.setData({
          model: 'no_rent',
          macno: ''
        });
      } else if (res.data.code == -55) {
        that.setData({
          model: 'no_car',
          macno: ''
        });
      } else if (res.data.code == 1) {
        if (that.data.macno != '') {
          wx2my.navigateTo({
            url: '/pages/select_car/select_car?macno=' + that.data.macno
          });
        } else if (that.data.rfid != '') {
          wx2my.navigateTo({
            url: '/pages/select_car/select_car?rfid=' + that.data.rfid
          });
        }

        that.setData({
          macno: '',
          rfid: ''
        });
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
      }
    });
  },

  getTradeTuan() {
    let that = this;
    app.wxRequest('get_trade_tuan', {
      'token': wx2my.getStorageSync('token'),
      'trade_id': that.data.tradeid
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        that.setData({
          macno: '',
          rfid: '',
          maxNum: res.data.data.nowTotal,
          tradeno: res.data.data.trade.tradeno
        });
        that.setData({
          model: 'JoinTrade'
        });
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
      }
    });
  },

  //租借
  toRent(e) {
    let that = this;
    that.getTmplID();
    let msgToken = wx2my.getStorageSync('token');

    if (msgToken == '' || msgToken == null) {
      that.setData({
        wrap: false
      });
    } else if (that.data.tradeid != '') {
      that.getTradeTuan();
    } else if (that.data.macno != '') {
      that.get_toRentStatus();
    } else if (that.data.rfid != '') {
      that.get_toRentStatus();
    } else if (that.data.tradeid != '') {
      that.get_toRentStatus();
    } else {
      wx2my.scanCode({
        success: res => {
          console.log(res);
          var res = res.result;

          if (res.indexOf('macno') < 0 && res.indexOf('rfid') < 0 && res.indexOf('tradeid') < 0) {
            wx2my.showToast({
              icon: 'none',
              title: '二维码无效'
            });
          } else if (res.indexOf('macno') > 0) {
            let macno = app.fm.getUrlParam('macno', res);
            wx2my.setStorageSync('macno', macno);
            that.setData({
              macno: macno,
              rfid: ""
            });
            app.wxRequest2('ZhanHuiLogin', {
              // 展会租借随机开柜并登录系统
              'macno': macno
            }, function (res) {
              if (res.data.code == 1) {
                let token = res.data.data.token;
                let trade_id = res.data.data.trade_id;
                wx2my.setStorageSync('token', token);
                that.setData({
                  model: 'open_timeout',
                  macno: "",
                  isZhanHui: true,
                  trade_id: trade_id
                });
              } else {
                that.get_toRentStatus();
              }
            });
          } else if (res.indexOf('rfid') > 0) {
            let rfid = app.fm.getUrlParam('rfid', res);
            wx2my.setStorageSync('rfid', rfid);
            that.setData({
              rfid: rfid,
              macno: ""
            });
            that.get_toRentStatus();
          } else if (res.indexOf('tradeid') > 0) {
            let tradeid = app.fm.getUrlParam('tradeid', res);
            wx2my.setStorageSync('tradeid', tradeid);
            that.setData({
              tradeid: tradeid,
              macno: ""
            });
            that.getTradeTuan();
          }
        }
      });
    }
  },

  doorSus() {
    that.setData({
      model: ""
    });
  },

  failOpenagain() {
    let that = this;
    if (that.data.onOff) return false;
    that.setData({
      onOff: 1
    });
    app.wxRequest('reopen_door', {
      'token': wx2my.getStorageSync('token'),
      'trade_id': that.data.trade_id
    }, function (res) {
      console.log(res);

      if (res.data.code == 100) {
        that.setData({
          model: 'open_timeout',
          onOff: 0
        });
      } else if (res.data.code == -100) {
        app.toast(res.data.msg);
        that.setData({
          model: 'door_openFail',
          onOff: 0
        });
      } else if (res.data.code == -33) {
        app.toast(res.data.msg);
        that.setData({
          model: 'open_timeout',
          onOff: 0
        });
      } else {
        app.toast(res.data.msg);
        setTimeout(() => {
          wx2my.reLaunch({
            url: '/pages/home/home'
          });
        }, 2000);
      }
    });
  },

  getTmplID() {
    console.log('已接收消息1');
    return;
    wx.requestSubscribeMessage({
      tmplIds: ['ynoGomAlFNgq7hVqsafW-F5aW6U3i1MgbOPfIHD6bpA', 'LH2ZJWFh8iAsETvW1mOud8xZfwL4VavA0NCtI_tLThY'],

      success(res) {
        console.log(res);

        if (res['ynoGomAlFNgq7hVqsafW-F5aW6U3i1MgbOPfIHD6bpA'] === 'accept') {
          console.log('用户同意了');
        }
      },

      fail(err) {
        //失败
        console.error(err);
        reject();
      }

    });
  },

  //归还
  toReturn(e) {
    let that = this;
    that.getTmplID();
    let msgToken = wx2my.getStorageSync('token');

    if (msgToken == '' || msgToken == null) {
      that.setData({
        wrap: false
      });
    } else {
      wx2my.navigateTo({
        url: '/pages/user_order/user_order'
      });
    }
  },

  //归还玩具打开柜门
  back_toy() {
    let that = this;
    app.wxRequest('back_toy', {
      'token': wx2my.getStorageSync('token'),
      'macno': that.data.macno
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        let yun_id = res.data.data.yun_id;
        that.setData({
          model: 'open_sus',
          yun_id: yun_id
        });
        that.get_backStatus();
      } else if (res.data.code == -22) {
        that.setData({
          model: 'back_noOrder',
          macno: ''
        });
      } else if (res.data.code == -33) {
        that.setData({
          model: 'no_chest',
          macno: ''
        });
      } else if (res.data.code == -44) {
        that.setData({
          model: 'open_fail',
          yun_id: res.data.data.yun_id
        });
      } else if (res.data.code == -55) {
        that.setData({
          model: 'have_return',
          macno: ''
        });
      } else if (res.data.code == -77) {
        that.setData({
          model: 'back_mistake',
          macno: ''
        });
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
      }
    });
  },

  //归还状态
  get_backStatus() {
    let that = this;
    app.wxRequest('polling_back_toy', {
      'yun_id': that.data.yun_id
    }, function (res) {
      if (res.data.code == 1) {
        app.toast(res.data.msg);
        that.setData({
          macno: '',
          model: 'return_sus',
          disinfect_time: res.data.data.disinfect_time
        });
        setTimeout(() => {
          that.setData({
            model: 'pay_sus'
          });
        }, 3000);
        wx2my.hideLoading();
      } else if (res.data.code == 0) {
        wx2my.showLoading({
          title: '归还中',
          mask: true
        });
        that.data.stopPull = setTimeout(function () {
          that.get_backStatus();
        }, 2000);
      } else if (res.data.code == 2) {
        let trade_id = res.data.data.trade_id;
        that.setData({
          macno: '',
          model: 'return_sus',
          disinfect_time: res.data.data.disinfect_time
        });
        setTimeout(() => {
          that.setData({
            model: ''
          });
          wx2my.navigateTo({
            url: '/pages/pay_order/pay_order?trade_id=' + trade_id
          });
        }, 2000);
        wx2my.hideLoading();
      } else if (res.data.code == -11) {
        that.setData({
          model: 'power_fail'
        });
        wx2my.hideLoading();
      } else if (res.data.code == -22) {
        that.setData({
          model: 'hand_mistake'
        });
        wx2my.hideLoading();
      } else if (res.data.code == -50) {
        that.setData({
          model: 'hand_fail'
        });
        wx2my.hideLoading();
      } else if (res.data.code == -60) {
        that.setData({
          model: 'order_noYour',
          macno: ''
        });
        wx2my.hideLoading();
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
        wx2my.hideLoading();
      }
    });
  },

  cancel() {
    this.setData({
      wrap: true,
      rfid: '',
      macno: '',
      tradeid: '',
      tradeno: ''
    });
  },

  //联系客服总平台
  toCall() {
    let that = this;
    app.wxRequest('customer', {}, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        let phone = res.data.data.tel;
        wx2my.showModal({
          title: '温馨提示',
          content: '拨打电话:' + res.data.data.tel,

          success(res) {
            if (res.confirm) {
              wx2my.makePhoneCall({
                phoneNumber: phone
              });
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }

        });
      }
    });
  },

  //故障联系客服
  tel() {
    let that = this;
    wx2my.showModal({
      title: '提示',
      content: '拨打电话:' + that.data.phoneNum,

      success(res) {
        if (res.confirm) {
          wx2my.makePhoneCall({
            phoneNumber: that.data.phoneNum
          });
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }

    });
  },

  //开门失败重新开门
  openAgain() {
    let that = this;
    that.setData({
      model: '',
      openAgain: ''
    });
    that.get_doorOpenstatus();
  },

  get_doorOpenstatus() {
    let that = this;
    app.wxRequest('reopen_door', {
      'token': wx2my.getStorageSync('token'),
      'yun_id': that.data.yun_id
    }, function (res) {
      console.log(res);

      if (res.data.code == 100) {
        that.get_backStatus();
        that.setData({
          model: 'open_sus'
        });
      } else if (res.data.code == -100) {
        that.setData({
          model: 'open_fail'
        });
      } else {
        that.setData({
          model: '',
          macno: ''
        });
        app.toast(res.data.msg);
      }

      that.setData({
        openAgain: 'openAgain'
      });
    });
  },

  del() {
    this.setData({
      have_coupon: true,
      wrap: true,
      model: '',
      macno: '',
      rfid: '',
      tradeid: '',
      tradeno: ''
    });
  },

  lookOther() {
    this.setData({
      model: ''
    });
    this.bindcallouttap(null);
  },

  howToUse() {
    this.setData({
      model: 'video'
    });
  },

  /**播放视屏 */
  play(e) {
    //执行全屏方法  
    var videoContext = wx.createVideoContext('myvideo', this);
    videoContext.requestFullScreen();
    this.setData({
      fullScreen: true
    });
  },

  /**关闭视屏 */
  closeVideo() {
    //执行退出全屏方法
    var videoContext = wx.createVideoContext('myvideo', this);
    videoContext.exitFullScreen();
  },

  /**视屏进入、退出全屏 */
  fullScreen(e) {
    var isFull = e.detail.fullScreen; //视屏全屏时显示加载video，非全屏时，不显示加载video

    this.setData({
      fullScreen: isFull
    });
  },

  getvideoLink() {
    let that = this;
    app.wxRequest('getvideoLink', {}, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        that.setData({
          videoLink: res.data.data
        });
      }
    });
  },

  //有一个未支付的订单
  toOrder() {
    this.setData({
      model: '',
      macno: ''
    });
    wx2my.navigateTo({
      url: '/pages/user_order/user_order?typeid=' + 0
    });
  },

  closeVideo() {
    this.setData({
      model: ''
    });
  },

  //有一个体验的订单正在进行
  toLookOrder() {
    this.setData({
      model: '',
      macno: ''
    });
    wx2my.navigateTo({
      url: '/pages/user_order/user_order?typeid=' + 3
    });
  },

  //订单支付成功查看订单
  underwayOrder() {
    this.setData({
      model: '',
      macno: ''
    });
    wx2my.navigateTo({
      url: '/pages/user_order/user_order?typeid=' + 3
    });
  },

  //正在进行中两个订单
  lookContinue() {
    this.setData({
      model: '',
      macno: ''
    });
    wx2my.navigateTo({
      url: '/pages/user_order/user_order?typeid=' + 3
    });
  },

  //继续租借
  again() {
    let that = this;
    this.setData({
      model: ''
    });
    wx2my.navigateTo({
      url: '/pages/select_car/select_car?macno=' + that.data.macno + '&marker=' + 1
    });
    this.setData({
      macno: ''
    });
  },

  //用户协议
  toAgree() {
    wx2my.navigateTo({
      url: '/pages/user_agreement/user_agreement'
    });
  },

  //充值中心
  apply() {
    let that = this;

    if (!app.fm.gain('token')) {
      that.setData({
        wrap: false
      });
    } else {
      that.setData({
        macno: ''
      });
      wx2my.navigateTo({
        url: '/pages/recharge/recharge'
      });
    }
  },

  onUnload: function () {
    let that = this;
    clearTimeout(that.data.stopPull);
    that.setData({
      model: ''
    });
  },
  //视图改变
  bindchangeTap: function (ev) {
    let that = this; // if (ev.type == "end") {
    //   that.refreshMap();
    // }

    let mapCtx = wx.createMapContext('map');
    mapCtx.getCenterLocation({
      success: function (res) {
        let lat = res.latitude;
        let lng = res.longitude;
        that.setData({
          ["markers[0].latitude"]: lat,
          //修改数组对象中的某一项
          ["markers[0].longitude"]: lng
        });
      }
    });
  },

  queding() {
    this.setData({
      model: ''
    });

    if (wx2my.getStorageSync('wrap') == true) {
      this.setData({
        wrap2: true
      });
    } else {
      this.setData({
        wrap2: false
      });
      return;
    }

    let that = this;
    app.wxRequest('add_trade_tuan', {
      'token': wx2my.getStorageSync('token'),
      'trade_id': that.data.tradeid,
      'num': that.data.num
    }, function (res) {
      console.log(res);
      that.setData({
        macno: '',
        rfid: '',
        tradeid: ''
      });

      if (res.data.code == 1) {
        that.setData({
          model: 'JoinTradeSuccess'
        });
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
      }
    });
  },

  cancel() {
    this.setData({
      model: ''
    });
    this.setData({
      macno: '',
      rfid: '',
      tradeid: ''
    });
  },

  //事件处理函数

  /*点击减号*/
  bindMinus() {
    var num = this.data.num;

    if (num > 1) {
      num--;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  /*点击加号*/
  bindPlus() {
    var num = this.data.num;
    console.log(num);

    if (num < this.data.maxNum) {
      num++;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  /*输入框事件*/
  bindManual(e) {
    var num = e.detail.value;
    console.log(e);

    if (num > this.data.maxNum) {
      num = this.data.maxNum;
    }

    if (num < 1) {
      num = 1;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  //绑定微信手机号
  getPhoneNumber(e) {
    console.log(e);

    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      let that = this;
      let msg = e;
      that.bindPhone(msg);
    } else {
      app.toast('请绑定手机号');
    }
  },

  bindPhone(msg) {
    var that = this;
    app.wxRequest('get_user_phone', {
      'type': 'weixin',
      'encryptedData': encodeURIComponent(msg.detail.encryptedData),
      'code': that.data.appCode,
      'iv': encodeURIComponent(msg.detail.iv)
    }, function (res) {
      console.log(res);

      if (res.data.code = 1) {
        let userInfo = res.data.data.phone ? JSON.parse(res.data.data.phone) : '';
        console.log(userInfo, "asdfgasdfasdgasdgasdg");

        if (!userInfo) {
          app.toast('手机号获取失败,请重新获取');
        } else {
          app.wxRequest('edit', {
            'account': userInfo
          }, function (res) {
            console.log(res);

            if (res.data.code == 1) {
              that.setData({
                wrap2: true
              });
              wx2my.setStorageSync('wrap', true);
            } else if (res.data.code == -1005) {
              app.toast(res.data.msg);
              that.setData({
                wrap2: true
              });
              wx2my.setStorageSync('wrap', true);
            }
          });
        }
      } else {
        app.toast(res.data.msg);
      }
    });
  },

  //是否绑定 手机号 
  permiss(e) {
    let that = this;
    app.wxRequest('profile', {}, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        console.log(res.data.data.account);

        if (res.data.data.account == '') {
          //未绑定
          that.setData({
            wrap: false
          });
        }

        if (!that.data.appCode) {
          wx.login({
            success: function (e) {
              console.log(e);
              that.setData({
                appCode: e.code
              });
            }
          });
        }
      } else {
        wx2my.showToast({
          icon: 'none',
          title: res.data.msg,
          duration: 2000
        });
      }
    });
  }

});